<template>
  <div class="app-container">
    <el-table border :data="tableDatas" size="mini" stripe>
      <el-table-column v-if="formData.PATIENT_ID && false" type="expand">
        <div class="mg12">
          <el-descriptions
            border
            :column="6"
            content-class-name="contentClass"
            label-class-name="labelClass"
            title="患者信息"
          >
            <el-descriptions-item
              v-for="(item, index) in patientAttrs"
              :key="index"
              :label="item.label"
            >
              {{ getAttr(formData, item.name) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="mg12">
          <el-descriptions
            border
            :column="6"
            content-class-name="contentClass"
            label-class-name="labelClass"
            title="检验信息"
          >
            <el-descriptions-item
              v-for="(item, index) in checkItemsSystem"
              :key="index"
              :label="item.CHECK_NAME"
            >
              {{ item.CHECK_RESULT.toString().replace('[]', '') }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-table-column>
      <el-table-column align="center" label="申请单号" width="148">
        <div>
          <div class="flex">
            <input
              ref="apply_num"
              v-model="APPLY_NUM"
              class="input input-1"
              placeholder="申请单号"
              type="text"
              @keyup="search"
            />
            <el-button icon="el-icon-caret-bottom" @click="showBloodApplies" />
          </div>
        </div>
      </el-table-column>
      <el-table-column align="center" label="住院号" prop="INP_NO" width="80" />
      <el-table-column
        align="center"
        label="ID号"
        prop="PATIENT_ID"
        width="80"
      />
      <el-table-column
        align="center"
        label="开单科室"
        prop="DEPT_NAME"
        width="120"
      />
      <el-table-column align="center" label="受血者" prop="PAT_NAME" width="80">
        <template #default="scope">
          <b class="font16 color-primary">{{ scope.row.PAT_NAME }}</b>
        </template>
      </el-table-column>
      <el-table-column align="center" label="费别" prop="FEE_TYPE" width="80" />
      <el-table-column
        align="center"
        label="输血目的"
        prop="BLOOD_PURPOSE"
        width="80"
      />
      <el-table-column
        align="center"
        label="血型 | RHD"
        prop="blood_group"
        width="90"
      >
        <template #default="scope">
          <div v-if="scope.row && scope.row.PAT_BLOOD_GROUP">
            <b class="font20" :class="getAboRhdClass(scope.row)">
              {{
                getAttr(scope.row, 'PAT_BLOOD_GROUP') +
                ' | ' +
                getAttr(scope.row, 'RH')
              }}
            </b>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="复检血型 | RHD"
        prop="recheck_blood_group"
        width="110"
      >
        <template #default="scope">
          <div v-if="scope.row && scope.row.RECHECK_BLOOD_GROUP">
            <b
              class="font20"
              :class="
                getClass(scope.row, 'PAT_BLOOD_GROUP', 'RECHECK_BLOOD_GROUP')
              "
            >
              {{ getAttr(scope.row, 'RECHECK_BLOOD_GROUP') }}
            </b>
            <b class="font20">|</b>
            <b class="font20" :class="getClass(scope.row, 'RH', 'RECHECK_RH')">
              {{ getAttr(scope.row, 'RECHECK_RH') }}
            </b>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="RH分型"
        prop="RH_TYPING"
        width="72"
      >
        <template #default="scope">
          <div v-if="scope.row && scope.row.RH_TYPING">
            {{ getAttr(scope.row, 'RH_TYPING') }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="申请日期"
        prop="APPLY_DATE"
        width="90"
      >
        <template #default="scope">
          {{ scope.row.APPLY_DATE ? scope.row.APPLY_DATE.substr(0, 10) : '' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="诊断"
        prop="BLOOD_DIAGNOSE"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column align="center" label="抗筛" prop="SOP" width="80">
        <template #default="scope">
          <div v-if="scope.row && scope.row.SOP">
            <b
              class="font24"
              :class="scope.row.SOP === '-' ? 'color-success' : 'color-danger'"
            >
              {{ getAttr(scope.row, 'SOP') }}
            </b>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别" prop="PAT_SEX" width="80" />
      <el-table-column align="center" label="年龄" prop="AGE" width="80" />
      <el-table-column
        align="center"
        label="旧标本号"
        prop="HISTORY_APPLY_NUM"
        width="80"
      >
        <template #default="scope">
          {{ getAttr(scope.row, 'HISTORY_APPLY_NUM') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="旧标本血型 | RHD"
        prop="NODATA"
        width="130"
      >
        <template #default="scope">
          {{ getAttr(scope.row, 'HISTORY_BLOOD_GROUP') }} |
          {{ getAttr(scope.row, 'HISTORY_RH') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="收到时间" prop="NULL" width="80" />
    </el-table>
    <div class="h12" />
    <el-container>
      <el-aside width="540px">
        <apply
          :check-items="checkItems"
          :h-g-b="HGB"
          :p-l-t="PLT"
          @fillMatchRecord="fillMatchRecord"
        />
        <history
          ref="history"
          :blood-match-records="bloodMatchRecords"
          @clearMatchRecords="clearMatchRecordsOnly"
          @fillMatchRecords="fillMatchRecords"
          @saveMatchRecords="saveMatchRecords"
        />
      </el-aside>
      <el-main style="padding: 0 0 0 12px">
        <blood
          :bloods="bloods"
          @addBloodMatchRecord="addBloodMatchRecord"
          @changeBloodMatchCategory="changeBloodMatchCategory"
        />
      </el-main>
    </el-container>
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      title="用血申请"
      :visible.sync="dialogVisible"
      width="1100px"
    >
      <applies @selectBloodApply="selectBloodApply" />
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :title="title"
      :visible.sync="dialogReportVisible"
      width="800px"
      @close="dialogReportClose"
    >
      <report :blood-match="reportData" />
    </el-dialog>
    <print ref="print" name="match" />
  </div>
</template>

<script>
  import Apply from './component/apply'
  import History from './component/history'
  import Blood from './component/blood'
  import Applies from './component/applies'
  import Report from '../report'
  import Print from '@/components/Print'
  import { patientAttrs, bloodGroups, bloodRhds } from '@/utils/constant'
  import { getCurrentTime, deepClone, getAttr, convertArr2Obj } from '@/utils'
  // eslint-disable-next-line no-unused-vars
  import { PLAK0001, PLAK0011, PLAK0014, PLAE0034 } from '@/api/client'
  import { PLAK0021 as getList } from '@/api/client'
  import { mapGetters } from 'vuex'
  export default {
    components: {
      Print,
      Apply,
      History,
      Blood,
      Applies,
      Report,
    },
    props: {
      activeName: {
        type: String,
        default() {
          return 'first'
        },
      },
    },
    data() {
      return {
        PLT: '',
        HGB: '',
        APPLY_NUM: '',
        formData: {},
        tableDatas: [{}],
        patientAttrs,
        checkItems: [],
        checkItemsSystem: [],
        bloods: [],
        bloodsClone: [],
        bloodMatchRecords: [],
        dialogVisible: false,
        dialogReportVisible: false,
        title: '',
        reportData: {},
        query: {
          BLOOD_GROUP: '',
          BLOOD_TYPE: 'ALL',
          APPLY_NUM: '',
          bloodMatchType: '',
        },
        bloodGroups,
        bloodRhds,
      }
    },
    computed: {
      ...mapGetters({
        bloodMatchTypes: 'initialData/bloodMatchTypes',
        bloodMatchTypeId: 'initialData/bloodMatchTypeId',
        bloodMatchTypeInitial: 'initialData/bloodMatchType',
        userid: 'user/userid',
      }),
      bloodMatchType() {
        const bloodMatchTypesObj = convertArr2Obj(this.bloodMatchTypes, 'id')
        const bloodMatchTypesObjInner = convertArr2Obj(
          bloodMatchTypesObj[this.bloodMatchTypeId[0]]['children'],
          'id'
        )[this.bloodMatchTypeId[1]]
        return bloodMatchTypesObjInner['name']
      },
      bloodGroupRhdEqual() {
        if (this.formData.PAT_BLOOD_GROUP) {
          if (this.formData.RECHECK_RH && this.formData.RECHECK_BLOOD_GROUP) {
            const blood_group_equal =
              this.formData.RECHECK_BLOOD_GROUP ===
              this.formData.PAT_BLOOD_GROUP
            const blood_rhd_equal =
              this.formData.RECHECK_RH === this.formData.RH
            return blood_group_equal && blood_rhd_equal
          }
        }
        return true
      },
      bloodMatchTypeFormat() {
        let arr = []
        this.bloodMatchTypes.forEach((item) => {
          arr = arr.concat(item.children)
        })
        const arrObj = convertArr2Obj(arr, 'id')
        let res = []
        this.bloodMatchTypeInitial.forEach((item) => {
          const temp = arrObj[item.slice(-1)[0]]
          res.push({
            blood_match_type_pid: temp['pid'],
            blood_match_type_id: temp['id'],
            blood_match_type_name: temp['name'],
            FIRST_RESULT: '',
            SECOND_RESULT: '',
            AGGREGATION_INTENSITY: '',
            MATCH_RESULT: '',
          })
        })

        return res
      },
    },
    watch: {
      bloodMatchTypePid() {
        if (this.activeName === 'first') {
          this.getCanMatchBloods()
        }
      },
    },
    methods: {
      getAboRhdClass(row) {
        const map = {
          A: 'color-primary',
          B: 'color-warning',
          O: 'color-success',
          AB: 'color-danger',
        }
        return map[row.PAT_BLOOD_GROUP]
      },
      search(e) {
        const keycode = window.event ? e.keyCode : e.which
        if (keycode === 13) {
          this.searchRow()
        }
      },
      selectBloodApply(row) {
        this.APPLY_NUM = row.APPLY_NUM
        this.searchRow()
        this.dialogVisible = false
      },
      searchRow() {
        if (!this.APPLY_NUM) {
          this.$message.error('请输入输血申请单号')
          return false
        } else {
          this.clearMatchRecordsPre()
          PLAK0001({ APPLY_NUM: this.APPLY_NUM }).then((res) => {
            this.formData = res.data
            this.HGB = getAttr(this.formData, 'HEMATIN')
            this.PLT = getAttr(this.formData, 'PLATELET')
            this.tableDatas = [this.formData]
            let checkItems = res.data.BLOOD_CAPACITYS.BLOOD_CAPACITY
            if (checkItems && checkItems.item) {
              checkItems = checkItems.item
            }
            if (!Array.isArray(checkItems)) {
              checkItems = [checkItems]
            }
            this.checkItems = checkItems
            if (this.checkItems.length > 0) {
              this.checkItems = this.checkItems.map((val) => {
                val.BLOOD_PURPOSE = this.formData.BLOOD_PURPOSE || ''
                return val
              })
            }

            let checkItemsSystem =
              (this.formData.APPLY_CHECK_ITEMS &&
                this.formData.APPLY_CHECK_ITEMS.APPLY_CHECK_ITEM) ||
              []
            if (checkItemsSystem && checkItemsSystem.item) {
              checkItemsSystem = checkItemsSystem.item
            }
            if (!Array.isArray(checkItemsSystem)) {
              checkItemsSystem = [checkItemsSystem]
            }
            this.checkItemsSystem = checkItemsSystem || []

            this.query.BLOOD_GROUP = this.formData.PAT_BLOOD_GROUP
            // this.query.APPLY_NUM = this.formData.APPLY_NUM
            this.query.bloodMatchType = this.bloodMatchType
            this.getCanMatchBloods()

            // if (!this.bloodGroupRhdEqual) {
            //   this.$baseMessage(
            //     '该患者初复检血型或Rhd不一致，请留意',
            //     'error',
            //     'vab-hey-message-danger'
            //   )
            // }

            if (this.formData.RH === '-' || this.formData.RECHECK_RH === '-') {
              this.$alert('该患者初检RH或复检RH为阴性，请留意', '操作提醒', {
                type: 'warning',
              })
            }
          })
        }
      },
      getCanMatchBloods() {
        if (!this.bloodGroupRhdEqual) {
          this.$confirm('该患者初复检血型或Rhd不一致, 是否继续配血?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.PLAK0034()
            })
            .catch(() => {
              console.log('cancel')
            })
        } else {
          this.PLAK0034()
        }

        // PLAE0034()
        // PLAE0034({ PATIENT_ID: this.formData.PATIENT_ID }).then((res) => {
        //   const data = res.data.filter((val) => {
        //     return val.RESULT === '阳性' || val.RESULT === '+'
        //   })
        //   if (data.length > 0) {
        //     this.$confirm('该患者曾有过抗筛阳性记录, 是否继续?', '提示', {
        //       confirmButtonText: '确定',
        //       cancelButtonText: '取消',
        //       type: 'warning',
        //     })
        //       .then(() => {
        //         this.PLAK0034()
        //       })
        //       .catch(() => {
        //         console.log('cancel')
        //       })
        //   } else {
        //     this.PLAK0034()
        //   }
        // })
      },
      PLAK0034() {
        this.bloods = []
        this.query.APPLY_NUM = this.APPLY_NUM
        PLAK0011(this.query).then((res) => {
          this.bloods = res.data
          this.bloodsClone = deepClone(this.bloods)
          this.bloodsClone = this.formatBloodsClone(
            this.bloodsClone,
            this.query.BLOOD_GROUP
          )
        })
      },
      formatBloodsClone(bloods, blood_group) {
        const arr = blood_group.split('^')
        let res = []
        arr.forEach((val) => {
          res = res.concat(bloods.filter((item) => item.BLOOD_GROUP === val))
        })
        return res
      },
      fillMatchRecord(row) {
        this.bloodMatchRecords.push({
          bloodApplyItem: row,
          TRANS_DATE: row.TRANS_DATE,
          MATCH_TIME: getCurrentTime(),
        })
      },
      async addBloodMatchRecord(row, index) {
        // 填充左侧配血记录区
        const bloodMatchRecordsClone = deepClone(this.bloodMatchRecords)
        const needs = bloodMatchRecordsClone.filter((val) => {
          return val.BLOOD_ID_UP === undefined
        })
        if (needs.length > 0) {
          needs[0] = Object.assign(needs[0], row)
        }
        this.bloodMatchRecords = bloodMatchRecordsClone

        // 将右侧可配血液列表中去除掉当前记录
        if (needs.length > 0) {
          this.bloods.splice(index, 1)
        }
      },
      clearMatchRecordsOnly() {
        this.bloodMatchRecords = []
        this.$refs.history.clearMultipleTable()
      },
      clearMatchRecords() {
        // this.bloods = deepClone(this.bloodsClone)
        // this.$refs.history.clearMultipleTable()
        // this.bloodMatchRecords = []
        this.clearMatchRecordsPre()
        this.APPLY_NUM = ''
        this.$refs.apply_num.focus()
      },
      clearMatchRecordsPre() {
        this.formData = {} // 重置表单数据
        this.checkItems = []
        this.tableDatas = [{}] // 重置表格为初始空行
        this.bloods = deepClone(this.bloodsClone)
        this.$refs.history.clearMultipleTable()
        this.bloodMatchRecords = []
      },
      saveMatchRecords(submitData) {
        if (submitData.matchRecords.length > 0) {
          // if (!this.formData.RECHECK_BLOOD_GROUP || !this.formData.RECHECK_RH) {
          //   this.$baseMessage(
          //     '未获取到标本检验数据，请先到标本检验菜单中增加标本检验数据',
          //     'error',
          //     'vab-hey-message-danger'
          //   )
          //   return
          // }

          if (!this.bloodGroupRhdEqual) {
            this.$confirm(
              '该患者初复检血型或Rhd不一致, 是否继续配血?',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
            )
              .then(() => {
                this.PLAK0014(submitData)
              })
              .catch(() => {
                console.log('cancel')
                // this.$refs.history.resetBtn()
              })
          } else {
            this.PLAK0014(submitData)
          }
        } else {
          this.$baseMessage('请选择配血记录', 'error', 'vab-hey-message-error')
          this.$refs.history.resetBtn()
        }
      },
      PLAK0014(submitData) {
        let reportData = deepClone(this.formData)
        reportData.BLOODS = submitData.matchRecords

        let BLOOD_IDS = submitData.matchRecords.map((val) => {
          return { BLOOD_REC_ID: { BLOOD_ID: val.BLOOD_ID } }
        })
        if (BLOOD_IDS.length === 1) {
          BLOOD_IDS = BLOOD_IDS[0]
        }
        const PARALIST = {
          BLOOD_MATCH_PARA: {
            APPLY_NUM: this.formData.APPLY_NUM,
            OPERATOR_NO: this.userid,
            RECHECK_BLOOD_GROUP: this.formData.RECHECK_BLOOD_GROUP,
            RECHECK_RH: this.formData.RECHECK_RH,
            MATCH_SUB_NUM:
              +submitData.matchRecords[0].bloodApplyItem.MATCH_SUB_NUM,
            MATCH_METCH: this.bloodMatchType,
            BLOOD_REC_IDS: BLOOD_IDS,
            blood_match_types: this.bloodMatchTypeFormat,
          },
        }
        PLAK0014(PARALIST)
          .then((res) => {
            this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
            this.clearMatchRecords()
            reportData.MATCH_SHEET_NUM =
              res.data.BLOOD_FEE_PRICE_CURRENT.MATCH_SHEET_NUM || ''
            this.reportData = reportData
            // this.dialogReportVisible = true
            this.handleDetail(reportData)
            // this.clearMatchRecords()
            // setTimeout(() => {
            //   this.dialogReportClose()
            // }, 2000)
          })
          .catch((err) => {
            if (err.message.indexOf('插入住院费用明细异常，请手工划价') > -1) {
              this.$baseAlert(err.message)
            }
          })
          .finally(() => {
            setTimeout(() => {
              this.$refs.history.resetBtn()
            }, 2000)
          })
      },
      dialogReportClose() {
        this.$baseEventBus.$emit('reload-router-view')
      },
      fillMatchRecords() {
        this.$emit('fillMatchRecords', 'fourth')
      },
      showBloodApplies() {
        this.dialogVisible = true
      },
      changeBloodMatchCategory(val) {
        let abos = ''
        switch (this.formData.PAT_BLOOD_GROUP) {
          case 'A':
            abos = 'O^A'
            break
          case 'B':
            abos = 'O^B'
            break
          case 'AB':
            abos = 'O^A^B^AB'
            break
          case 'O':
            abos = 'O'
            break
        }
        this.query.BLOOD_GROUP =
          +val === 1 ? this.formData.PAT_BLOOD_GROUP : abos
        this.getCanMatchBloods()
      },
      getAttr(formData, field) {
        return getAttr(formData, field)
      },
      getClass(row, field, field_compare) {
        if (row && row[field]) {
          return row[field] === row[field_compare]
            ? 'color-success'
            : 'color-danger'
        }
        return ''
      },
      async handleDetail(row) {
        const queryForm = {
          APPLY_NUM: row.APPLY_NUM,
          MATCH_SHEET_NUM: row.MATCH_SHEET_NUM,
        }

        const { data } = await getList(queryForm).catch(() => {
          this.listLoading = false
        })
        row = data[0]
        row.BLOODS = data
        this.bloodMatch = row
        // this.dialogVisible = true
        this.$refs.print.show(row)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .input {
    width: 88px;
    padding: 6px 12px 6px 12px;
    margin-right: -6px;
    border: 1px solid #ddd;
    border-radius: 4px;
    outline: none;
    &:focus,
    &:hover {
      border: 1px solid #bbb;
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
</style>
